import SockJS from "sockjs-client";
import { Stomp } from "@stomp/stompjs";

// 创建WebSocket服务类
class OrderWebSocketService {
    constructor() {
        this.sockjs = null;
        this.stompClient = null;
        this.connected = false;
        this.subscriptions = new Map(); // 存储订阅ID和订阅对象
        this.baseUrl = "http://192.168.10.103:8081/ws/order";
    }

    /**
     * 建立连接
     * @param {Object} options - 连接选项
     * @param {string} [options.token] - 认证令牌
     * @param {Function} [options.onConnect] - 连接成功回调
     * @param {Function} [options.onDisconnect] - 断开连接回调
     * @param {Function} [options.onError] - 错误回调
     */
    connect(options = {}) {
        // 如果已连接则先断开
        if (this.connected) {
            this.disconnect();
        }

        // 创建SockJS实例
        this.sockjs = new SockJS(this.baseUrl);

        // 创建STOMP客户端
        this.stompClient = Stomp.over(this.sockjs);

        // 禁用调试日志（生产环境），开发环境可开启
        this.stompClient.debug = () => {};

        // 连接头信息（可包含认证信息）
        const headers = options.token
            ? { Authorization: `Bearer ${options.token}` }
            : {};

        // 建立连接
        return new Promise((resolve, reject) => {
            this.stompClient.connect(
                headers,
                // 连接成功回调
                (frame) => {
                    this.connected = true;
                    console.log("STOMP连接成功", frame);
                    options.onConnect?.(frame);
                    resolve(frame);
                },
                // 连接错误回调
                (error) => {
                    this.connected = false;
                    console.error("STOMP连接错误", error);
                    options.onError?.(error);
                    reject(error);
                }
            );
        });
    }

    /**
     * 订阅消息主题
     * @param {string} topic - 订阅主题（如：/topic/order-updates）
     * @param {Function} callback - 消息处理回调函数
     * @param {Object} [headers] - 订阅头信息
     * @returns {string} 订阅ID
     */
    subscribe(topic, callback, headers = {}) {
        if (!this.connected || !this.stompClient) {
            console.error("未建立连接，无法订阅");
            return null;
        }

        // 订阅主题
        const subscription = this.stompClient.subscribe(
            topic,
            (message) => {
                console.log(`收到消息: ${message.body}`)
                try {
                    // 尝试解析JSON消息
                    const data = JSON.parse(message.body);
                    callback(data, message);
                } catch (error) {
                    // 非JSON格式直接返回
                    callback(message.body, message);
                }
            },
            headers
        );
        console.log(subscription,"订阅成功=====")
        // 存储订阅信息
        this.subscriptions.set(subscription.id, subscription);
        return subscription.id;
    }

    /**
     * 取消订阅
     * @param {string} subscriptionId - 订阅ID
     */
    unsubscribe(subscriptionId) {
        if (this.subscriptions.has(subscriptionId)) {
            this.subscriptions.get(subscriptionId).unsubscribe();
            this.subscriptions.delete(subscriptionId);
            console.log(`已取消订阅: ${subscriptionId}`);
        }
    }

    /**
     * 发送消息
     * @param {string} destination - 消息目的地（如：/app/order-request）
     * @param {Object|string} data - 发送的数据
     * @param {Object} [headers] - 消息头信息
     */
    send(destination, data, headers = {}) {
        if (!this.connected || !this.stompClient) {
            console.error("未建立连接，无法发送消息");
            return;
        }

        // 处理消息体
        const messageBody =
            typeof data === "object" ? JSON.stringify(data) : data;

        // 发送消息
        this.stompClient.send(
            destination,
            {
                "content-type": "application/json",
                ...headers,
            },
            messageBody
        );
    }

    /**
     * 断开连接
     */
    disconnect() {
        if (this.stompClient && this.connected) {
            // 取消所有订阅
            this.subscriptions.forEach((subscription) => {
                subscription.unsubscribe();
            });
            this.subscriptions.clear();

            // 断开连接
            this.stompClient.disconnect(() => {
                this.connected = false;
                this.stompClient = null;
                this.sockjs = null;
                console.log("STOMP连接已断开");
            });
        }
    }

    /**
     * 获取连接状态
     * @returns {boolean} 连接状态
     */
    isConnected() {
        return this.connected;
    }
};

// 导出单例实例
export default new OrderWebSocketService();
